﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;

namespace Comet
{
    class Imgur
    {

        public static void Handle(HttpListenerContext context)
        {
            try
            {
                byte[] buffer;
                using (BinaryReader br = new BinaryReader(context.Request.InputStream))
                {
                    buffer = br.ReadBytes(Convert.ToInt32(context.Request.ContentLength64));
                }

                HttpWebRequest oRequest = (HttpWebRequest)HttpWebRequest.Create("http://api.imgur.com/2/upload.json");
                oRequest.ContentType = context.Request.ContentType;
                oRequest.Method = "POST";

                oRequest.ContentLength = buffer.Length;

                using (Stream output = oRequest.GetRequestStream())
                {
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }

                string responseString;

                using (StreamReader responseReader = new StreamReader(oRequest.GetResponse().GetResponseStream()))
                {
                    responseString = responseReader.ReadToEnd();
                }

                string imageID = Regex.Match(responseString, "hash\":\"([^<]+)\",\"deletehash").Groups[1].Value;

                File.AppendAllText("c:\\comet\\config\\imgur.txt", imageID + Environment.NewLine);

                string iframehtml = "<script type='text/javascript'>parent.UploadComplete('" + imageID + "');</script>";

                Communications.SendResponse(context, Communications.DataType.Text, iframehtml);
            }
            catch
            {
                Communications.SendResponse(context, Communications.DataType.Text, "<script type='text/javascript'>parent.UploadComplete('none');</script>");
            }


        }

    }
}
